package com.rimi.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @author chengliang
 * 创建时间 2020/3/25 9:27
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置过编码格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
//        1. 导入jar
//        2. 实例化 硬盘文件项工厂 、RequestParse
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
//        3. 通过RequestParse类 去 解析 Request对象，获取到表单中所有的数据
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            //4. 遍历所有的数据并判断哪些是文件哪些是普通的表单属性
            for (FileItem fileItem : fileItems) {
                //是文件还是普通的表单属性
                if(fileItem.isFormField()){
                    //普通表单字段
                    System.out.println(fileItem.getFieldName());
                    System.out.println(fileItem.getString());
                }else{
                    //文件
                    System.out.println("出现一个文件");
                    //IO流，文件内容都认为是一个输入流
                    InputStream inputStream = fileItem.getInputStream(); //获取到文件的内容
                    //文件名全称（根据浏览器不同可能出现文件路径 test.sql   D://develop/sql/test.sql）
                    //用来处理文件名相同出现覆盖的问题
                    String fileName = UUID.randomUUID().toString().replace("-",""); //"-"
                    String name = fileItem.getName();
                    int i = name.lastIndexOf(".");
                    if(i != -1){
                        fileName = fileName + name.substring(i); // 123123514123.sql asdfadsfasdfsdf.txt
                    }
                    //用来处理文件名中存在路径的问题
//                    int i = fileName.lastIndexOf("\\"); //i == -1 没有文件路径
//                    if(i != -1){
//                        fileName = fileName.substring(i+1);
//                    }

                    //通过 IO流 将文件保存到服务器(本机)
                    //String fileUploadPath = "D://"; //linux系统 cdef盘
                    //当前项目的服务器中的路径
                    String fileUploadPath = req.getServletContext().getRealPath("/upload/");
                    File file = new File(fileUploadPath);
                    //如果路径不存在，则创建该路径
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    System.out.println(fileUploadPath);
                    //5. 将文件保存到服务器中
                    //获取到文件保存路径的输出流对象(D://test.sql)
                    OutputStream outputStream = new FileOutputStream(new File(file,fileName));
                    //定义字节数组(每次读取2048个字节大小的内容)
                    byte[] bytes = new byte[2048];
                    while (inputStream.read(bytes) != -1){
                        outputStream.write(bytes);
                        outputStream.flush();
                    }
                    //文件保存完毕
                    outputStream.close();
                    inputStream.close();
                }
            }
//
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println("解析Request失败");
        }



    }


}
